package com.cskaoyan.wordmemorize.controller.admin;

import com.cskaoyan.wordmemorize.auth.SaAdminCheckPermission;
import com.cskaoyan.wordmemorize.auth.StpKit;
import com.cskaoyan.wordmemorize.common.result.Result;
import com.cskaoyan.wordmemorize.dto.admin.*;
import com.cskaoyan.wordmemorize.request.*;
import com.cskaoyan.wordmemorize.dto.admin.PageDTO;
import com.cskaoyan.wordmemorize.request.VocCommand;
import com.cskaoyan.wordmemorize.service.FileUploadService;
import com.cskaoyan.wordmemorize.service.VocChapterService;
import com.cskaoyan.wordmemorize.service.VocService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@Tag(name = "后台管理-物料管理-单词管理相关接口")
@RestController
@RequestMapping("admin/voc")
public class AdminVocController {

    @Resource
    VocService vocService;
    @Resource
    VocChapterService vocChapterService;


    @Autowired
    FileUploadService fileUploadService;

    // @Resource
    // FileUploadService fileUploadService;




    @Operation(summary = "****添加单词",
            description = "主要用于物料管理-单词管理",
            responses = {
                    @ApiResponse(
                            responseCode = "200",
                            description = "登出成功"

                    ),
                    @ApiResponse(responseCode = "500",
                            description = "请求失败"
                    )
            }

    )
    @PostMapping("")
    //@SaAdminCheckPermission("admin:voc:add")
    public Result addVocabulary(@RequestBody VocCommand command) {
        vocService.addVoc(command);
        return Result.ok();
    }
    //
    @GetMapping ("list")
    //@SaAdminCheckPermission("admin:voc:add")
    //PageDTO<VocDTO> getVocabularies(VocPageRequest pageQuery);
    public Result<PageDTO<VocDTO>> getVocabularies( VocPageRequest vocPageRequest) {
        PageDTO<VocDTO> vocabularies = vocService.getVocabularies(vocPageRequest);
        return Result.ok(vocabularies);
    }
    //修改单词
    @PutMapping ()
    //@SaAdminCheckPermission("admin:voc:update")
    public Result updateVocabulary(@RequestBody VocCommand command) {
        vocService.updateVoc(command);
        return Result.ok();
    }

    //删除指定单词
    @DeleteMapping("{vocId}")
    @SaAdminCheckPermission("admin:voc:delete")
    public Result deleteVocabulary(@PathVariable("vocId") Long vocId) {
        vocService.deleteVocabulary(vocId);
        return Result.ok();
    }

    //批量删除单词
    @DeleteMapping("")
    @SaAdminCheckPermission("admin:voc:batchdelete")
    public Result deleteVocabularies(@RequestBody BatchDeleteCommand command) {
        vocService.deleteVocabularies(command);
        return Result.ok();
    }
    //校验上传单词的excel表格
    @PostMapping("excel/validate")
    @SaAdminCheckPermission("admin:voc:excel:upload")
    public Result vocExcelVerify(@RequestParam("vocExcel") MultipartFile file) throws IOException {
        vocService.vocExcelValidate(file);
        return Result.ok();
    }
    //通过excel表格上传单词
    @PostMapping("excel")
    @SaAdminCheckPermission("admin:voc:excel:upload")
    public Result addVocExcel(@RequestParam("vocExcel") MultipartFile file) throws IOException {
        Long employeeId = StpKit.ADMIN.getLoginIdAsLong();
        vocService.addVocExcel(file, employeeId);
        return Result.ok();
    }

    //指定单词的单词-章节-书籍关系列表
    @GetMapping("relations/{vocId}")
    //    List<VocChapBookDTO> getVocRelations(Long vocId);
    public Result getVocRelations(@PathVariable("vocId") Long vocId) {
        return Result.ok(vocService.getVocRelations(vocId));
    }
    //删除单词音频文件
    @PostMapping("file/{type}/{id}")
    //DeleteVocFileOperateDTO deleteFile(Long id, String type, String name);
    public Result deleteFile(@PathVariable("type") String type,
                             @PathVariable("id") Long id,
                             @Param("name") String name) {
        return Result.ok(vocService.deleteFile(id, type, name));
    }
    //删除单词与书籍和章节的关系
    @DeleteMapping("relation/{id}")
    //DeleteVocRelationOperateDTO deleteVocRelation(Long id);
    public Result deleteVocRelation(@PathVariable("id") Long id) {
        return Result.ok(vocService.deleteVocRelation(id));
    }
    //删除单词释义
    @DeleteMapping("interpretation/{id}")
    //DeleteInterpretationOperateDTO deleteInterpretation(Long id);
    public Result deleteInterpretation(@PathVariable("id") Long id) {
        return Result.ok(vocService.deleteInterpretation(id));
    }
    //删除单词例句
    @DeleteMapping("example/{id}")
    //DeleteVocExampleOperateDTO deleteExample(Long id);
    public Result deleteExample(@PathVariable("id") Long id) {
        return Result.ok(vocService.deleteExample(id));
    }
    //上传单词对应的音频文件
    @PostMapping("file")
    public Result uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        String path = fileUploadService.upload(file);
        return Result.ok(path);
    }
    //下载单词的excel表格模版
    @GetMapping("template")
    public ResponseEntity<byte[]> downloadTemplate(String type) throws IOException {
        // 使用ClassPathResource读取资源文件

        ClassPathResource resource;

        if ("single".equals(type)) {
            resource  = new ClassPathResource("templates/单选题模版.xlsx");
        } else if ("fill".equals(type)) {
            resource = new ClassPathResource("templates/填空题模版.xlsx");
        } else {
            resource = new ClassPathResource("templates/单词上传模版.xlsx");
        }
        // 检查文件是否存在
        if (!resource.exists()) {
            return ResponseEntity.notFound().build();
        }

        // 读取文件内容
        InputStream inputStream = resource.getInputStream();
        byte[] fileBytes = IOUtils.toByteArray(inputStream);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment",
                URLEncoder.encode(resource.getFilename(), "UTF-8"));

        return ResponseEntity.ok()
                .headers(headers)
                .body(fileBytes);
    }

    @GetMapping("chapters/list")
    //    PageDTO<VocChapterDTO> getChapterPage(VocChapterPageRequest pageQuery);
    public Result getChapterPage(VocChapterPageRequest pageQuery) {
        PageDTO<VocChapterDTO> chapterPage = vocChapterService.getChapterPage(pageQuery);
        return Result.ok(chapterPage);
    }

    @PostMapping("chapter")
        // 添加章节(后端-物料管理-章节管理)
    //void addChapter(VocChapterCommand command);
    public Result addChapter(@RequestBody VocChapterCommand command) {
        vocChapterService.addChapter(command);
        return Result.ok();
    }

    @PutMapping("chapter")
        // 修改章节(后端-物料管理-章节管理)
    //void updateChapter(VocChapterCommand command);
    public Result updateChapter(@RequestBody VocChapterCommand command) {
        vocChapterService.updateChapter(command);
        return Result.ok();
    }

    @DeleteMapping("chapters")
        // 批量删除选中章节(后端-物料管理-章节管理)
    //List<DeleteChapterOperateDTO> deleteChapters(BatchDeleteCommand command);
    public Result deleteChapters(@RequestBody BatchDeleteCommand command) {
        List<DeleteChapterOperateDTO> deleteChapterOperateDTOS = vocChapterService.deleteChapters(command);
        return Result.ok(deleteChapterOperateDTOS);
    }

    @DeleteMapping("chapter/{chapterId}")
        // 删除章节(后端-物料管理-章节管理)
    //DeleteChapterOperateDTO deleteChapter(Long chapterId);
    public Result deleteChapter(@PathVariable @Parameter(description = "章节id") Long chapterId) {
        DeleteChapterOperateDTO data = vocChapterService.deleteChapter(chapterId);
        return Result.ok(data);
    }
}
